package com.fwmagic.webmagic;

import us.codecraft.webmagic.Page;
import us.codecraft.webmagic.Site;
import us.codecraft.webmagic.Spider;
import us.codecraft.webmagic.processor.PageProcessor;

import java.util.List;
import java.util.concurrent.atomic.AtomicLong;

/**
 * 爬取风中一匹狼博客（csdn）
 */
public class YbBlogPageProcessor implements PageProcessor {

    private Site site = Site.me().setDomain("blog.csdn.net").setRetryTimes(3).setCharset("UTF-8").setSleepTime(1000);

    //详情页表达式
    private static final String URL_PATTERN = "http://blog\\.csdn\\.net/millery22/article/details/\\w+";

    private final AtomicLong count = new AtomicLong(0);

    @Override
    public void process(Page page) {
        //取详情页数据
        if(page.getUrl().regex(URL_PATTERN).match()){
            page.putField("标题",page.getHtml().xpath("//div[@class='article_title']/h1/span/a/text()"));
            if(page.getResultItems().get("标题")==null){
                page.setSkip(true);
            }else{
                page.putField("地址",page.getUrl());
                page.putField("发布时间",page.getHtml().xpath("//div[@class='article_r']/span/text()"));
                count.incrementAndGet();//+1
                System.out.println("==========【兴趣e族】共抓取到"+count+"条有效数据============");
            }
        }else{
            //发现详情页
            page.addTargetRequests(page.getHtml().links().regex(".*/millery22/article/details/\\w+").all());
            //发现下一页
            page.addTargetRequests(page.getHtml().css("div#papelist").links().regex(".*/millery22/article/list/\\w+").all());
        }
    }

    @Override
    public Site getSite() {
        return site;
    }

    public static void main(String[] args) {
        Spider.create(new YbBlogPageProcessor()).addUrl("http://blog.csdn.net/millery22/article/list/1").thread(3).run();
    }
}
